﻿using AutoMapper;
using Common;
using Common.Result;
using Model.Dto;
using Model.Entitys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    public class UserService : IUserService
    {
        private readonly IMapper _mapper;
        public UserService(IMapper mapper)
        {
            _mapper = mapper;
        }
        public async Task<bool> AddUserAsync(UserReq userReq)
        {
            var res=await DbContext.db.Insertable(_mapper.Map<Users>(userReq)).ExecuteCommandAsync();
            if(res==1)
            {
                return true;
            }
            return false;
        }

        public async Task<bool> DeleteUserByIdAsync(int id)
        {
            var res=await DbContext.db.Deleteable<Users>().In(id).IsLogic().ExecuteCommandAsync();
            if(res>=1) { return true; }
            return false;
        }

        public async Task<UserRes> GetUserByIdAsync(int id)
        {
            Users user=await DbContext.db.Queryable<Users>()
                .Where(it=>it.Isdeleted==false)
                .FirstAsync(it=>it.Id==id);
            return _mapper.Map<UserRes>(user);
        }

        public async Task<PageInfo> GetUserPageInfoAsync(int pageNum, int pageSize, string? username)
        {
            RefAsync<int> total = 0;
            var userList=await DbContext.db.Queryable<Users>()
                .Where(it => it.Isdeleted == false)
                .WhereIF(!string.IsNullOrEmpty(username),it=>it.Username.Contains(username))
                .ToPageListAsync(pageNum,pageSize,total);
            return new PageInfo { Total = total,Data= _mapper.Map<List<UserRes>>(userList) };
        }

        public async Task<bool> UpdateUserByIdAsync(UserReq userReq)
        {
            var res=await DbContext.db.Updateable(_mapper.Map<Users>(userReq)).IgnoreColumns(it=>it.CreateTime).ExecuteCommandAsync();
            if(res>=1) { return true;}
            return false;
        }
    }
}
